#include "tgbot_service.h"
#include "tgbotmgr.h"
#include "json.h"
#include "util.h"

#define TG_API_MSG_MAX_LENGTH 2048 // api消息长度限制为4096  设置为2048便于查看

static std::string tg_api_head = "https://api.telegram.org/bot";
static std::string tg_api = "/sendMessage";
static std::map<std::string,std::string> http_json_heads = {{"Content-Type","application/json"}};

void TgBotService::SendMessageToTgGroup()
{
    std::map<std::string, BotInfo>& bots = TgBotMgr::Instance()->GetAllBots();
    if(bots.empty())
    {
        log_error("no bot");
        return;
    }

    // 遍历所有bot
    for (auto& pair : bots)
    {
        // 获取bot信息
        BotInfo& bot_info = pair.second;
        auto& botMsg_que = bot_info.botMsg_queue;

        // bot消息队列为空 直接跳过该bot
        if(botMsg_que.empty())
        {
            continue;
        }

        // 是否进入下个发送周期
        const std::uint64_t current_time = CTools::GetUnixTime();
        const std::uint64_t send_interval = (bot_info.send_limit > 1) ? bot_info.send_limit : 1;
        if(bot_info.last_times != 0 && current_time - bot_info.last_times < send_interval)
        {
            log_debug("skip send msg, last_times: %s, GetUnixTime: %s, right_res: %s;",std::to_string(bot_info.last_times).c_str(), std::to_string(CTools::GetUnixTime()).c_str(), std::to_string((bot_info.send_limit > 1)? bot_info.send_limit: 1).c_str());
            continue;// 未到下个发送周期，跳过bot本次发送
        }
        log_debug("star send msg, last_times: %s, GetUnixTime: %s, php_cfg send_limit: %s;",std::to_string(bot_info.last_times).c_str(), std::to_string(CTools::GetUnixTime()).c_str(), std::to_string((bot_info.send_limit > 1)? bot_info.send_limit: 1).c_str());


        // 拼接发送消息  换行隔开
        std::string body_str="";
        while(!botMsg_que.empty())
        {
            auto& temp = botMsg_que.front();
            // api请求  消息长度限制4096
            if(temp.msg_text().size() + body_str.size() >= TG_API_MSG_MAX_LENGTH)
            {
                break;// 超过长度限制，则不拼接本条消息
            }
            body_str += temp.msg_text() + "\n";
            botMsg_que.pop();
        }


        // 拼接丢包统计
        log_debug("dis_msg_count: %s", std::to_string(bot_info.dis_msg_count).c_str());
        if(current_time / 86400 != bot_info.last_times / 86400)
        {
            bot_info.dis_msg_count = 0;// 跨天清空丢包统计
        }
        if(bot_info.dis_msg_count > 0)
        {
            body_str += "今天丢弃消息数：" + std::to_string(bot_info.dis_msg_count) + "\n";
        }


        // 遍历bot所在群组  广播消息
        const std::string& req_url_api = tg_api_head + bot_info.tgBotToken + tg_api;
        Json::Value req_body;
        Json::FastWriter writer;

        int send_limit_s  = 0;
        for(const auto& t : bot_info.chat_ids)
        {
            if(send_limit_s >= 25)
            {
                log_debug("send_limit_s: %s,", std::to_string(send_limit_s).c_str());
                break;//TGAPI 单bot 每秒限制发送25条
            }

            if(t.empty())
            {
                log_error("chat_id is empty;");
                continue;// 群组id为空跳过
            }
  
            req_body["text"] = body_str;
            req_body["chat_id"] = t;
            std::string req_str = writer.write(req_body);
            log_debug("send message show, chat_id:%s, msg_text:%s;", t.c_str(), req_str.c_str());

            std::uint32_t event_id = 0;
            if(!Ctx.msg_router.sendHttpPOST(req_url_api, req_str, http_json_heads, event_id)) {
                log_error("sendHttpPOST Failed, req_url: %s, body_str: %s;", req_url_api.c_str(), req_str.c_str());
                continue;// 发送失败 跳过当前群组
            }

            // 更新 消息发送时间戳 发送次数
            bot_info.last_times = CTools::GetUnixTime();
            send_limit_s++;

            auto handleLambda = [](std::string& body, long is_ok)
            {
                log_debug("Resp body: %s, is_ok: %s;", body.c_str(), is_ok ? "true" : "false");

                Json::Reader reader;
                Json::Value resp;
                if (!reader.parse(body, resp)) {
                    log_error("Resp Parse Failed, Error Message: %s;", reader.getFormattedErrorMessages().c_str());
                    return;
                }
                log_debug("Resp Parse Success");

                
                // 检查 "ok" 字段是否存在且为布尔值
                if (!resp.get("ok", false).asBool()) {
                    log_error("Resp Failed Message: %s", resp.toStyledString().c_str());

                    // 获取错误信息
                    int resp_error_code = resp.get("error_code", 0).asInt();
                    std::string resp_description = resp.get("description", "Unknown error").asString();
                    log_error("Resp Error Code: %d, Description: %s;", resp_error_code, resp_description.c_str());

                    // 错误码处理
                    if (resp_error_code == 429) {
                        int retry_time = resp["parameters"].get("retry_after", 0).asInt();
                        log_error("Resp Error Code 429, Wait %d s, try again", retry_time);
                    } else if (resp_error_code == 403) {
                        log_error("Resp bot remove from group, please check");
                    }
                    else {
                        log_error("Resp Error Code: %d, Message: %s;", resp_error_code, resp_description.c_str());
                    }
                    return;
                }

                // 解析返回结果
                const auto& result = resp["result"];
                std::string group_name = result["chat"].get("title", "null").asString();
                std::string msg_text = result.get("text", "null").asString();

                log_debug("Resp Send Message Success, Group Name: %s;", group_name.c_str());
            };
        
            Ctx.msg_router.AddCurlEvent(event_id, handleLambda);
        }

    }
}















